dojo.provide("miaigo.controller.BaseController");

dojo.require("miaigo.model.MoveReference");

dojo.declare(
    "miaigo.controller.BaseController",
    null,
    {
	// attached views
	// [miaigo.view.BaseView]
	_views: null,

	// game models
	// [ {model: miaigo.model.Game, cursor: miaigo.model.MoveReference} , ... ]
	_models: null,

	// The active model
	_currentModelIndex: -1,

	constructor: function()
	{
	    this._views = [];
	    this._models = [];
	},

	// attach a view to make the view controlled by this controller
	attachView: function(/* miaigo.view.BaseView */view)
	{
	    this._views.push(view);
	    view.onAttached(this);
	},

	detachView: function(/* miaigo.view.BaseView */view)
	{
	    var index = dojo.indexOf(this._views, view);
	    if (index >= 0)
	    {
		this._views.splice(index, 1);
		view.onDetached(this);
	    }
	},

	// add a game model
	addModel: function(/* miaigo.model.Game */model)
	{
	    this._models.push( {model: model, cursor: null} );

	    if (this._currentModelIndex < 0)
	    {
		this._currentModelIndex = 0;
		this.onCurrentModelChanged(this.activeModel());
	    }
	},

	addCollection: function(/* miaigo.model.Collection */collection)
	{
	    for (var i = 0; i < collection.getGameCount(); i++)
	    {
		this.addModel(collection.getGame(i));
	    }
	},

	// events
	onCurrentModelChanged: function(/* miaigo.model.Game */model)
	{
	},

	onCurrentMoveChanged: function(/* miaigo.model.Move */move)
	{
	},

	// methods

	// return: miaigo.model.Game
	activeModel: function()
	{
	    if (this._models[this._currentModelIndex])
	    {
		return this._models[this._currentModelIndex].model;
	    }

	    return null;
	},

	activeModelCursor: function()
	{
	    if (this._models[this._currentModelIndex])
	    {
		if (!this._models[this._currentModelIndex].cursor)
		{
		    this._models[this._currentModelIndex].cursor =
			new miaigo.model.MoveReference(this.activeModel());
		}

		return this._models[this._currentModelIndex].cursor;
	    }

	    return null;
	},

	nextMove: function()
	{
	    var cursor = this.activeModelCursor();
	    if (cursor)
	    {
		cursor.next();
		this.onCurrentMoveChanged(cursor.getMove());
	    }
	},

	prevMove: function()
	{
	    var cursor = this.activeModelCursor();
	    if (cursor)
	    {
		cursor.prev();
		this.onCurrentMoveChanged(cursor.getMove());
	    }
	}
    });